package com.ganlucode.sipmock.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sip.*;
import javax.sip.address.AddressFactory;
import javax.sip.header.HeaderFactory;
import javax.sip.message.MessageFactory;

/**
 * @author GanLu
 * @date 2020-05-14 19:36
 */
@Configuration
public class SipConfiguration {

    public final static String TRANSPORT_TCP = "TCP";

    public final static String TRANSPORT_UDP = "UDP";

    @Autowired
    private SipServerProperties sipServerProperties;

    @Autowired
    private SipStackProperties sipStackProperties;

    @Bean
    public SipFactory sipFactory(){
        SipFactory sipFactory = SipFactory.getInstance();
        sipFactory.setPathName("gov.nist");
        return sipFactory;
    }

    @Bean
    public SipStack sipStack(@Autowired SipFactory sipFactory) throws PeerUnavailableException {
        SipStack sipStack = sipFactory.createSipStack(sipStackProperties);
        return sipStack;
    }

    @Bean
    public AddressFactory addressFactory(@Autowired SipFactory sipFactory) throws PeerUnavailableException {
        AddressFactory addressFactory = sipFactory.createAddressFactory();
        return addressFactory;
    }

    @Bean
    public HeaderFactory headerFactory(@Autowired SipFactory sipFactory) throws PeerUnavailableException {
        HeaderFactory headerFactory = sipFactory.createHeaderFactory();
        return headerFactory;
    }

    @Bean
    public MessageFactory messageFactory(@Autowired SipFactory sipFactory) throws PeerUnavailableException {
        MessageFactory messageFactory = sipFactory.createMessageFactory();
        return messageFactory;
    }

    @Bean(name = "tcpSipProvider")
    public SipProvider tcpSipProvider(@Autowired SipStack sipStack) throws Exception {
        ListeningPoint tcpListeningPoint = sipStack.createListeningPoint(sipServerProperties.getSipIp(),
                sipServerProperties.getSipPort(), TRANSPORT_TCP);
        SipProvider tcpSipProvider = sipStack.createSipProvider(tcpListeningPoint);
        return tcpSipProvider;
    }

    @Bean(name = "udpSipProvider")
    public SipProvider udpSipProvider(@Autowired SipStack sipStack) throws Exception {
        ListeningPoint udpListeningPoint = sipStack.createListeningPoint(sipServerProperties.getSipIp(),
                sipServerProperties.getSipPort(), TRANSPORT_UDP);
        SipProvider udpSipProvider = sipStack.createSipProvider(udpListeningPoint);
        return udpSipProvider;
    }


}
